#!/bin/bash

# set -x

CMAKE=`type -P cmake`
DATE=`date +%Y%m%d`
GIT=`type -P git`
MAKE=`type -P make`
VERSION="--single-branch --branch 5.2.0"
#VERSION="--single-branch --branch 0.4.17.1"
#VERSION="--depth 1"

if [ -z "$DATE" ]
then
    echo "Cannot set the date. Stopping the program."
    exit 1
elif [ -z "$CMAKE" ]
then
     echo "Please install cmake program. Stopping the program."
     exit 1
elif [ -z "$GIT" ]
then
     echo "Please install git program. Stopping the program."
     exit 1
elif [ -z "$MAKE" ]
then
     echo "Please install make program. Stopping the program."
     exit 1
else

    # Configure mintest with : not in place, server, client, freetype, gettext, gles, spatial, sound, luajit, gmp, jsoncpp, and version
    
    CMAKEOPTIONS="-DRUN_IN_PLACE=TRUE -DBUILD_SERVER=TRUE -DBUILD_CLIENT=TRUE -DENABLE_FREETYPE=ON -DENABLE_GETTEXT=ON -DENABLE_GLES=OFF -DENABLE_SPATIAL=ON -DENABLE_SOUND=ON -DENABLE_LUAJIT=ON -DENABLE_SYSTEM_GMP=ON -DENABLE_SYSTEM_JSONCPP=OFF -DOPENGL_GL_PREFERENCE=LEGACY -DVERSION_EXTRA=${DATE}"
    INSTALLDIR=/usr/local
    MINETEST=$INSTALLDIR/minetest
    MINETESTGAME=games/minetest_game
    MINETESTGIT=https://github.com/minetest/minetest.git
    MINETESTGAMEGIT=https://github.com/minetest/minetest_game.git

    if [ -d $INSTALLDIR ]
    then
	cd $INSTALLDIR

	# backup existing folder
	
	if [ -d $MINETEST ]
	   then
	   echo "There's already an installation. Backing up the old one."
	   mv $MINETEST $MINETEST.$DATE
	fi

	# get most recent version of Minetest

	echo "Get the most recent version of Minetest"
	$GIT clone $VERSION $MINETESTGIT 

	# compile Minetest

	if [ -d $MINETEST ]
	then

	    echo "Compiling Minetest"
	    cd $MINETEST
	    $GIT clone $VERSION $MINETESTGAMEGIT $MINETESTGAME	    
	    $CMAKE . $CMAKEOPTIONS
	    $MAKE -j 3	    
	    echo "Minetest compiled and installed with success"
	    echo "To launch Minetest ; " $MINETEST/"bin/minetest" 
	else
	    echo "Check that directory " $INSTALLDIR\$MINETEST " is reachable."
	    exit 1
	fi
    else
	echo "The directory " $INSTALLDIR " isn't reachable. Stopping the program."
	exit 1
    fi
    exit 0
fi
